package comport

import (
	"fmt"
)

type ComDevice struct {
	com      SerialDevice
	call     func([]byte)
	portName string
	baud     int
}

func (w *ComDevice) Open(f func([]byte)) error {
	device, err := CreateDevice(w.portName, w.baud)
	w.call = f
	w.com = device
	if err == nil {
		w.com.OnDataArrival(w.call)
	}
	err = w.com.Open()
	return err
}

func (w *ComDevice) Init(keyPre string, config map[string]interface{}) error {
	v, ok := config[fmt.Sprintf("%vdevice.com", keyPre)]
	if ok && v != nil && v != "" {
		w.portName = v.(string)
	} else {
		return fmt.Errorf("串口配置错误")
	}
	v, ok = config[fmt.Sprintf("%vdevice.baud", keyPre)]
	if ok && v != nil && v != "" {
		w.baud = v.(int)
	} else {
		return fmt.Errorf("波特率配置错误")
	}
	return nil
}

func (w *ComDevice) Close() {
	if nil != w.com {
		w.com.Close()
	}
}

func (w *ComDevice) Send(d []byte) error {
	if w.com == nil {
		return fmt.Errorf("设备未初始化")
	}
	_, err := w.com.Write(d)
	return err
}
